package zhiziyibai.simpleweather.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import zhiziyibai.simpleweather.MainActivity;
import zhiziyibai.simpleweather.R;
import zhiziyibai.simpleweather.gson.Weather;
import zhiziyibai.simpleweather.util.HttpUtil;
import zhiziyibai.simpleweather.util.Utility;

public class AutoUpateService extends Service {
    /*后台更新服务*/

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        updateWeather();
        updateBingPic();
        AlarmManager manager= (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour=(int)(30*60*1000);//x小时毫秒数
        long triggerAtTime= SystemClock.elapsedRealtime()+anHour;
        Intent i=new Intent(this,AutoUpateService.class);
        PendingIntent pi=PendingIntent.getService(this,0,i,0);
        manager.cancel(pi);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
        return super.onStartCommand(intent, flags, startId);

    }
    /*更新天气*/
    private void updateWeather(){
        SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString =prefs.getString("weather",null);
        if (weatherString!=null){
            Weather weather= Utility.handleWeatherResponse(weatherString);
            String weatherId=weather.basic.weatherId;
            String weatherUrl="http://guolin.tech/api/weather?cityid="+weatherId+"&key=0a046c7967134d689d0a32b894be70c0";
            HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseText=response.body().string();
                    Weather weather=Utility.handleWeatherResponse(responseText);
                    if (weather!=null&&"ok".equals(weather.status)){
                        SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(AutoUpateService.this).edit();
                        editor.putString("weather",responseText);
                        editor.apply();
                        /*发起通知*/
                        Intent intent=new Intent(getBaseContext(), MainActivity.class);
                        PendingIntent pi=PendingIntent.getActivity(getBaseContext(),0,intent,0);
                        NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        Notification notification=new NotificationCompat.Builder(getBaseContext())
                                .setContentTitle(weather.basic.cityName)
                                .setContentText("现在气温是:"+weather.now.temperature+"℃")
                                .setWhen(System.currentTimeMillis())
                                .setSmallIcon(R.mipmap.jian)
                                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.jian))
                                .setContentIntent(pi)
                                .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.bg3)))
                                .build();
                        manager.notify(1,notification);

                    }
                }
            });
        }


    }
    /*更新必应每日一图*/
    private void updateBingPic(){
        final String requestBingPic="http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String bingPic=response.body().string();
                SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(AutoUpateService.this).edit();
                editor.putString("bing_pic",bingPic);
                editor.apply();
            }
        });
    }
}
